import { ref } from 'vue'
import { useMenuStore } from '@/stores/menu'
import { useRoute, onBeforeRouteUpdate, useRouter } from 'vue-router'
import { setTabList, getTabList } from '@/composables/cookie'

export function useTabList() {
    const menuStore = useMenuStore()
    const route = useRoute()
    const router = useRouter()

    // 当前被选中的 tab
    const activeTab = ref(route.path)
    // 导航栏 tab 数组
    const tabList = ref([
        {
            title: '仪表盘',
            path: "/admin/index"
        }
    ])
    function addTab(tab) {
        // 判断 tab 是否已经存在
        let isTabNotExisted = tabList.value.findIndex(item => item.path == tab.path) == -1
        // 如果不存在，则添加
        if (isTabNotExisted) {
            // 添加到导航栏 tab 数组
            tabList.value.push(tab)
        }
        setTabList(tabList.value)
    }
    function initTabList() {
        // 从 localStorage 中获取 tabList
        let tabs = getTabList()
        // 如果 localStorage 中有 tabList，则初始化
        if (tabs) {
            tabList.value = tabs
        }
    }

    initTabList()

    const removeTab = (path) => {
        let tabs = tabList.value
        // 当前被选中的 tab 标签
        let actTab = activeTab.value

        if (actTab == path) {
            // 删除当前选中的 tab
            tabs.forEach((tab, index) => {
                if (tab.path == path) {
                    // 拿到被选中的标签页下标，判断是否是最后一个标签页
                    let nextTab = tabs[index + 1] || tabs[index - 1]
                    if (nextTab) {
                        actTab = nextTab.path
                    }
                }
            })

        }
        // 需要被激活的标签页
        activeTab.value = actTab
        // 过滤掉被删除的标签页，重新设置回去
        tabList.value = tabs.filter(tab => tab.path != path)
        // 更新 localStorage 中的 tabList
        setTabList(tabList.value)
        // 切换标签页
        tabChange(activeTab.value)

    }
    onBeforeRouteUpdate((to, from) => {
        // 切换路由时，更新当前选中的 tab
        activeTab.value = to.path
        // 添加到导航栏 tab 数组
        addTab({
            title: to.meta.title,
            path: to.path
        })
    })
    const tabChange = (path) => {
        // 切换 tab 时，更新当前选中的 tab
        activeTab.value = path
        // 跳转路由
        router.push(path)
    }
    const handCloseTab = (command) => {
        // 首页路由
        let indexPath = '/admin/index'
        // 关闭其他标签页
        if (command == 'closeOthers') {
            // 过滤出首页和当前页
            tabList.value = tabList.value.filter((tab) => tab.path == indexPath || tab.path == activeTab.value)
        } else if (command == 'closeAll') { // 处理关闭全部
            // 切换为首页
            activeTab.value = indexPath
            // 只保留首页
            tabList.value = tabList.value.filter((tab) => tab.path == indexPath)
            // 切换标签页
            tabChange(activeTab.value)
        }
        setTabList(tabList.value)
    }
    return {
        menuStore,
        tabList,
        activeTab,
        removeTab,
        tabChange,
        handCloseTab
    }
}

